<?php

	namespace Admin\Model;
	use Think\Model;

	class GoodsModel extends Model{

		//商品ID
		protected $goods_id = '';

		public $_validate = [
			['number','','型号已经存在！',0,'unique',1],
	        // ['number','/^[A-Za-z0-9]+$/','您输入的类型格式错误！',1, 'regex'],
	        ['name','require','您输入的商品名格式错误！',1 , 'regex'],
	        ['color', '/^[{4e00}-\x{9fa5}]{1,20}$/u' , '您输入的颜色格式错误！' , 1 , 'regex' ],
	        ['price', '/^[0-9]*[1-9][0-9]*$/u' , '您输入的价格格式错误！' , 1 , 'regex' ],
		];
		//显示添加商品页操作
		public function addd(){
			$map['status'] = ['eq' , 1];
			$classify = $this->where($map)->order('concat(`path`,`id`) asc')->select();
		
			foreach ($classify as $key => &$value) {
				// 1.获取逗号的数量
				$num = substr_count($value['path'] , ',');
				$value['num'] = $num;
				//  2.重复一个字符串
        		$str = str_repeat('|---',$num - 1 );
        		$value['name'] = $str . $value['name'];
			}

			$det = M('details');
			$details = $det->select();


			return array($details , $classify);
		}

		//添加商品的处理
		public function append(){			

			$post = I('post.');

			$data['classify_id'] = $post['classify_id'];
			$data['number'] = $post['number'];
			$data['color'] = $post['color'];
			$data['price'] = $post['price'];
			$data['name'] = $post['name'];
			$data['name'] = htmlentities($data['name']);
			$data['name'] = strip_tags($data['name']);
			$data['addtime'] = time();
			$data['status'] = 0;


			$this->startTrans();

			//自动验证
			if ($this->create($data)) {
				//商品主表的添加
				$goods_res = $this->add($data);
				
				if ($goods_res) {

					$this->goods_id = $this->where($data)->select()[0]['goods_id'];

					//添加尺码表
					$de_res = $this->attr($post['details'] , $post['store']);


					if (!$de_res) {
						//不成功，则回滚
						$this->rollback();
					}

					//添加图片表
					$im_res = $this->image();

					if (!$im_res) {
						//不成功，则回滚
						$this->rollback();
					}
					
					// // 添加访问表
					$rep_res = $this->report();

					if (!$rep_res) {
						//不成功，则回滚
						$this->rollback();
					}
					$this->commit();
					return true;

				}else{

					//不成功，则回滚
					$this->rollback();
					return false;
				}

			}else{
				//不成功，则回滚
				$this->rollback();
				return false;
			}
		}

		// 添加尺码表
		public function attr($det , $sto){
			//添加尺码表
			$size_id = '';
			foreach ($det as $key => $value) {
				$list['goods_id'] = $this->goods_id;
				$list['details_id'] = $value['details'];

				//正则验证库存
				$preg = '/^\d{1,9}$/';
				if(!preg_match($preg,$sto[$key])){

					//不成功，则回滚
					return false;
				}

				$list['store'] = $sto[$key];

				$list['addtime'] = time();

				//添加尺码表ID
				$attr = M('attr');

				$size_res = $attr->add($list);

				if ($size_res == 0) {
					//不成功，则回滚
					return false;
				}
			}
			return true;
		}

		// 添加访问表
		public function report(){

			$report = M('report');

			$repo['goods_id'] = $this->goods_id;
			$repo['views'] = 0;
			$repo['access'] = 0;
			$repo['addtime'] = time();

			$report_res = $report->add($repo);

			if ($report_res == 0) {
				//不成功，则回滚
				return false;
			}
			return true;
		}

		// 添加图片上传表
		public function image(){
			$image = M('image');

			$config = array(    
				'maxSize'    =>    3145728,
			    'savePath'   =>    './Picture/Img/',    
			    'saveName'   =>    array('uniqid',''),    
			    'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),    
			    'autoSub'    =>    true,    
			    'subName'    =>    array('date','Ymd'),
			);

			$upload = new \Think\Upload($config);// 实例化上传类
			$info   =   $upload->upload();

			if(!$info) {
				// 上传错误提示错误信息    
				// $res = $upload->getError();

				return false;
			}else{
				// 上传成功 获取上传文件信息    
				$path = [];
				// 添加图像表
				foreach($info as $file){     
					$path['goods_id'] = $this->goods_id; 
					$path['addtime'] = time();
					$path['name'] = $file['savename'];
					$path['path'] = $file['savepath'];
					$path['addtime'] = time();
					$path['status'] = 1;

					$image_res = $image->add($path);

					if ($image_res == 0) {
						//不成功，则回滚
						return false;
					}
				}
			}
			return true;
		}


		// 商品展示
		public function show()
		{
			// 查询商品主表信息
			$data = $this->select();
			
			$time = time();
			// 显示文字状态
			$status = ['新发布' , '上架' , '下架'];
			foreach ($data as $key => &$value) {
				$list = [];	
				$value['status'] = $status[ $value['status'] ];
				// 显示格式日期	
				$value['addtime'] = date('Y-m-d' , $value['addtime']);

				//求取销量
				$map['goods_id'] = ['eq' , $value['goods_id'] ];
				$list[] = M('attr')->where($map)->select();

				//求取销量
				$sum = 0;
				if (count($list[0])) {
					foreach ($list as $key => $val1) {
					
						foreach ($val1 as $key => $val2) {
									$sum += $val2['sale'];
									$value['sale'] = $sum;
								}
					}
				}else{
					$value['sale'] = 0;
				}

				//获取商品ID查询图片
				$image = M('image');
				$map['goods_id'] = ['eq' , $value['goods_id']];
				$img = $image->where($map)->select()[0];

				$value['path'] = $img['path'] . $img['name'];
			}
			return $data;
			
		}


		//查看商品详情
		public function refer()
		{
			$id = I('get.id');
			$data = [];
			$map['goods_id'] = ['eq' , $id];
			// 查询商品主表信息
			$data['goods'] = $this->where($map)->select();

			$time = time();
			// 显示文字状态
			$status = ['新发布' , '上架' , '下架'];
			foreach ($data['goods'] as $key => &$value) {
				$value['status'] = $status[ $value['status'] ];
				// 显示格式日期	
				$value['addtime'] = date('Y-m-d' , $value['addtime']);

				//显示图片
				$image = M('image');
				$map['goods_id'] = ['eq' , $value['goods_id']];
				$img = $image->where($map)->select()[0];
				$value['path'] = $img['path'] . $img['name'];

			}

			// 查询尺码表
			$map['goods_id'] = ['eq' , $id ];
			$data['size'] = M('attr')->where($map)->select();
			foreach ($data['size'] as $key => &$value) {
				$value['addtime'] = date('Y-m-d' , $value['addtime']);
			}

			//获取尺码数据
			$size = [];
			foreach ($data['size'] as $key => &$value) {

				$details_id = $value['details_id'];

				$details = M('details');
				$map['details_id'] = ['eq' , $details_id ];
				$size = $details->field('size')->where($map)->select();
				$value['size'] = $size;
				
			}

			//查询报表
			$map['goods_id'] = ['eq' , $id ];
			$data['report'] = M('report')->where($map)->select();

			$data['report'][0]['addtime'] = &date('Y-m-d' , $data['report'][0]['addtime']);

			return $data;
		}

		
		//修改状态
		public function status()
		{	
			$goods_id = I('get.goods_id');
			$status = I('get.status');

			if ($status == '新发布') {
				$status = 1;
				$map['goods_id'] = ['eq' , $goods_id ];
				$data['status'] = $status;
				$res = $this->where($map)->save($data);
			}else if($status == '上架'){
				$status = 2;
				$map['goods_id'] = ['eq' , $goods_id ];
				$data['status'] = $status;
				$res = $this->where($map)->save($data);
			}else{
				$status = 1;
				$map['goods_id'] = ['eq' , $goods_id ];
				$data['status'] = $status;
				$res = $this->where($map)->save($data);
			}

			return $res;
		}

		// 删除尺码表
		public function del()
		{

			$attr_id = I('get.attr_id');
			$map['attr_id'] = ['eq' , $attr_id];
			$res = $this->where($map)->delete();
			return $res;

		}

		// 修改尺码表
		public function modify()
		{
			$attr_id = I('get.attr_id');
			$size = I('get.size');
			if (!empty($attr_id)) {
				// 修改界面
				$map['attr_id'] = ['eq' , $attr_id];
				$info = [];
				$res = $this->where($map)->select()[0];
				$info['size'] = $size;
				$info['attr_id'] = $res['attr_id'];
				$info['store'] = $res['store'];
				return $info;
			}else{
				// 修改的action
				$post = I('post.');
				$attr = M('attr');
				$store['store'] = $post['store'];
				$attr_id = I('post.attr_id');
				$map['attr_id'] = ['eq' , $attr_id];
				$res = $attr->where($map)->save($store);
				
				if ($res == 1) {
					return true;
				}
				if ($res ===  0) {
					return true;
				}	
				if ($res == false) {
					return false;
				}
				
			}
		}

		//商品图片展示
		public function img_show()
		{
			// $data = [];
			// $goods_id = I('get.goods_id');
			// $map['goods_id'] = $goods_id;
			// $map['status'] = ['egt','0'];
			// $order = "sort desc,image_id desc";
			// $list = $this->lists('image',$map,$order);
			// print_r($list);exit;
			// // 获取商品图片表image中状态为非-1的图片信息
			// $data['image_info'] = $this->where("goods_id = $goods_id and status in (0,1)")->order('sort desc,image_id desc')->select();
			// foreach ($data['image_info'] as $key => &$value) {
			// 	$time = time();
			// 	$value['addtime'] = date('Y/m/d' , $time);;
			// }
			// // 获取当前商品id的名称和型号
			// $img = D('goods');
			// $info = $img->where("goods_id={$goods_id}")->find();
			// $data['goods_name'] = $info['name'].$info['number'];
			// return $data;
		}

		//修改商品价格
		public function price(){

			$post = I('post.');
			$map['goods_id'] = ['eq' , $post['goods_id']];
			$data['price'] = $post['price'];
			$res = $this->where($map)->save($data);

			if ($res == 1) {
				return true;
			}

			if ($res == 0) {
				return true;
			}

			if ($res == false) {
				return false;
			}
		}

		// 添加尺码
		public function addsize(){
			$goods_id = I('get.goods_id');
			$attr = M('attr')->field('details_id')->where('goods_id = ' . $goods_id)->select();
			
			$details_id = '';
			foreach ($attr as $key => $value) {
				$details_id .= $value['details_id'] . ',';
			}	
			$details_id = rtrim($details_id , ',');

			$details = M('details')->field('details_id , size')->where(" details_id not in  ({$details_id })")->select();

			return $details;
		}


	};
